package other.xsy.passlys.receivable;

import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventRequest;
import com.rkhd.platform.sdk.data.model.Debooking__c;
import com.rkhd.platform.sdk.data.model.InvoiceDetail__c;
import com.rkhd.platform.sdk.data.model.Invoice__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.xsy.passlys.util.HCXObjectService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 删除开票主表：修改相关的开票金额字段
 * @Author 黎炎松
 * 2024-08-15 10:12
 */
public class InvoiceDel implements Trigger {
    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) throws Exception {
        InvoiceDel invoiceDel = new InvoiceDel();

        TriggerRequest request = new TriggerRequest();
        Invoice__c invoice = new Invoice__c();
        invoice.setId(3424412987202148L);
        invoice = hcxObjectService.get(invoice);
        request.setDataList(Arrays.asList(invoice));

        invoiceDel.execute(request);
    }


    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug("删除开票主表 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<XObject> objList = new ArrayList<>();
        for (XObject xObject : dataList) {
            objList.add(xObject);
            dataResultList.add(new DataResult(true, "", xObject));
        }

        // 获取明细下的 booking
        Object bookingStr = objList.get(0).getAttribute("bookingStr__c");
        if (bookingStr != null) {
            List<Long> bookingIdList = Arrays.stream(bookingStr.toString().split(",")).map(v -> Long.valueOf(v)).distinct().collect(Collectors.toList());

            // 触发修改相关开票字段
            logger.debug("删除开票主表 触发开始 bookingIdList " + bookingIdList);
            ReceivableService receivableService = new ReceivableService();
            receivableService.calcInvoiceAmounByBooking(bookingIdList);
        }

        return new TriggerResponse(true, "处理完成", dataResultList);
    }

}
